﻿using GodSharp;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZK.Common;
using ZK.Common.Log4;
using ZK.InterfaceServer;

namespace ZK.HardWareBLL
{
    /// <summary>
    /// 宁波柯力传感科技股份有限公司
    ///型号：D39-WA
    /// 比特率：建议2400
    /// 接受数据：9位
    /// </summary>
    public class NBKLD39WagonBalanceBLL
    {
        private readonly GodSerialPort _serialPort;
        private bool _isOpened;//打开状态
        private List<double> weightList;
        public decimal weighNow = 0;
        int weightListCount;
        private HaredWareCommonM wagonBalance;
        //public NBKLD39WagonBalance(HaredWareCommonM config)
        //{
        //    wagonBalance = config;
        //    _serialPort =
        //        new GodSerialPort(config.PortName, Convert.ToInt32(config.BaudRate), Parity.None, Convert.ToInt32(config.DataBits), StopBits.One)
        //        {
        //            EndCharOfHex = "03",
        //            DataFormat = SerialPortDataFormat.Hex,
        //            RtsEnable = true,
        //            DtrEnable = true
        //        };
        //    _serialPort.UseDataReceived((serialPort, bytes) =>
        //    {
        //        try
        //        {
        //            var weight = GetWeight(bytes);
        //            Common.DelegateHelper.WeightCallbackEvent?.Invoke(weight);
        //        }
        //        catch (Exception ex)
        //        {
        //            LogManage.WriteErr("获取地磅数据异常：" + ex.ToString());
        //            Common.DelegateHelper.InfoMessageEvent.Invoke("获取地磅数据异常");
        //        }
        //    });
        //    Open();
        //}
        private double nowWeight = 0;
        public NBKLD39WagonBalanceBLL()
        {
            weightListCount = Convert.ToInt32(AppConfigHelper.GetAppSettings("weightListCount"));
            weightList = new List<double>();
            wagonBalance = IConfig.GetSetwagonBalance;
            try
            {

                _serialPort =
                    new GodSerialPort(wagonBalance.PortName, Convert.ToInt32(wagonBalance.BaudRate), Parity.None, Convert.ToInt32(wagonBalance.DataBits), StopBits.One)
                    {
                        EndCharOfHex = "03",
                        DataFormat = SerialPortDataFormat.Hex,
                        RtsEnable = true,
                        DtrEnable = true
                    };
                _serialPort.UseDataReceived((serialPort, bytes) =>
                {
                    try
                    {
                        double weight = GetWeight(bytes);
                        if ((nowWeight != weight) && (ErrDate != weight))
                        {
                            nowWeight = weight;
                            Common.DelegateHelper.WeightCallbackEvent?.Invoke(weight);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManage.WriteErr("获取地磅数据异常：" + ex.ToString());
                        Common.DelegateHelper.InfoMessageEvent.Invoke("获取地磅数据异常");
                    }
                });
                Open();
            }
            catch (Exception ex)
            {
                AutoControlTransportApiServer.AddHardWareLog(wagonBalance.Name, 1, "串口通讯失败");
                Common.Log4.LogManage.WriteErr("初始化地磅 " + ex.ToString());
                Common.DelegateHelper.InfoMessageEvent.Invoke("初始化地磅失败！");
                //  Common.MessageDialog.MessageBoxShow("地磅数据异常！");
            }
        }

        public NBKLD39WagonBalanceBLL(string silo)
        {
            weightListCount = Convert.ToInt32(AppConfigHelper.GetAppSettings("weightListCount"));
            weightList = new List<double>();
            wagonBalance = IConfig.GetSetwagonBalance;
            try
            {

                _serialPort =
                    new GodSerialPort(wagonBalance.PortName, Convert.ToInt32(wagonBalance.BaudRate), Parity.Even, Convert.ToInt32(wagonBalance.DataBits), StopBits.Two)
                    {
                        EndCharOfHex = "03",
                        DataFormat = SerialPortDataFormat.Hex,
                        RtsEnable = true,
                        DtrEnable = true
                    };
                _serialPort.UseDataReceived((serialPort, bytes) =>
                {
                    try
                    {
                        double weight = GetWeight(bytes);
                        if ((nowWeight != weight) && (ErrDate != weight))
                        {
                            nowWeight = weight;
                            Common.DelegateHelper.WeightCallbackEvent?.Invoke(weight);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManage.WriteErr("获取地磅数据异常：" + ex.ToString());
                        Common.DelegateHelper.InfoMessageEvent.Invoke("获取地磅数据异常");
                    }
                });
                Open();
            }
            catch (Exception ex)
            {
                AutoControlTransportApiServer.AddHardWareLog(wagonBalance.Name, 1, "串口通讯失败");
                Common.Log4.LogManage.WriteErr("初始化地磅 " + ex.ToString());
                Common.DelegateHelper.InfoMessageEvent.Invoke("初始化地磅失败！");
                //  Common.MessageDialog.MessageBoxShow("地磅数据异常！");
            }
        }

        private int ErrDate = -1;
        /// <summary>
        /// 获取地磅数据
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
            private double GetWeight(byte[] bytes)
            {
                if (bytes.Length == 9)
                {
                    var number = 0;
                    number += (bytes[0] - 48);
                    number += (bytes[1] - 48) * 10;
                    number += (bytes[2] - 48) * 100;
                    // number += (bytes[3] - 46) * 1000;
                    number += (bytes[4] - 48) * 1000;
                    number += (bytes[5] - 48) * 10000;
                    number += (bytes[6] - 48) * 100000;
                    number += (bytes[7] - 48) * 1000000;
                    return (double)number / 1000;
                    //return number;
                }
                else
                {
                    Common.Log4.LogManage.WriteErr("获取地磅数据长度有误 erroor");
                    return -1;
                }
            }

        /// <summary>
        /// 打开地磅
        /// </summary>
        public void Open()
        {
            _isOpened = _serialPort.Open();
            if (!_isOpened)
            {
                LogManage.WriteErr("地磅打开失败 信息：" + Newtonsoft.Json.JsonConvert.SerializeObject(IConfig.GetSetwagonBalance));
                //MessageDialog.MessageBoxShow("地磅打开失败");
                AutoControlTransportApiServer.AddHardWareLog(wagonBalance.Name, 1, "地磅打开失败");
                Common.DelegateHelper.InfoMessageEvent.Invoke("地磅打开失败！");
            }
            //ReopenIfClosed();
        }
        /// <summary>
        /// 关闭地磅
        /// </summary>
        public void Close()
        {
            _isOpened = !_serialPort.Close();
        }
        /// <summary>
        /// 重新打开
        /// </summary>
        private void ReopenIfClosed()
        {
            if (_isOpened)
            {
                //await Task.Delay(1000);
                //await Task.Run(() =>
                //{
                //    if (!_serialPort.IsOpen)
                //    {
                //        _serialPort.Close();
                //        _serialPort.Open();
                //    }
                //    ReopenIfClosed();
                //});
            }
            else
            {
                _serialPort.Close();
            }
        }
    }
}
